package org.example.oop.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * org.example.oop.thread
 *
 * @author moLei
 * @description 同时开启两个线程，共同获取1-100之间的所有数字
 *          输出所有的奇数
 * @date 2025/6/25
 */
public class NumberExercises {

    private static int num = 0;

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();

        new Thread(() -> printNum(lock)).start();

        new Thread(() -> printNum(lock)).start();


    }

    /**
     * 打印数字
     * @param lock
     */
    private static void printNum(ReentrantLock lock) {
        while (true) {
            try {
                Thread.sleep(10);
                // 所需要加在判断外，不然的话可能会出现数字超出
                lock.lock();
                // 判断数字是否超过
                if (num < 100) {
                    num++;
                    if (num % 2 != 0) {
                        System.out.println(Thread.currentThread().getName() + "-----------------" + num);
                    }
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
